from aiogram import F, types, Router
from aiogram.filters import CommandStart, CommandObject
from aiogram.fsm.context import FSMContext
from loguru import logger

from database import models
from tg_bot.filters.command_filter import WithDeepLink
from tg_bot.filters.user_filter import IsActive
from tg_bot.keyboards import inline
from tg_bot.keyboards.callback_factory import BackCall
from tg_bot.states.user import PersonalAccount

router = Router()
router.message.filter(IsActive())


@router.message(CommandStart(), WithDeepLink(False))
async def personal_account(message: types.Message,
                           state: FSMContext,
                           user: models.TgUser):
    """
    Команда /start от зарегистрированного пользователя -> личный кабинет.

    ----
    :param message: Сообщение тг.
    :param state: Состояние пользователя.
    :param user: Пользователь.
    :return:
    """
    text = user.personal_account_text()
    key = await inline.concatenate_key(
        await inline.menu_keyboard(),
        await inline.balance_history(),
        await inline.voucher_keyboard()
    )
    await message.answer(text, reply_markup=key)
    await state.set_state(PersonalAccount.main)


@router.message(CommandStart(True, magic=F.args.isdigit()), WithDeepLink(True))
async def personal_account_with_link(message: types.Message,
                                     state: FSMContext,
                                     user: models.TgUser,
                                     command: CommandObject):
    """
    Команда /start с диплинком реферальной программы. Указываем реферала.

    ----
    :param message: Сообщение тг.
    :param state: Состояние пользователя.
    :param user: Пользователь.
    :param command: Команда с диплинком.
    :return:
    """
    user.set_invite_by(command.args)
    await personal_account(message, state, user)


@router.callback_query(BackCall.filter(
    F.to == 'personal_account'
))
async def personal_account_call(call: types.CallbackQuery,
                                state: FSMContext,
                                user: models.TgUser):
    """
    Переход в личный кабинет пользователя по инлайн кнопке "Назад"

    ----
    :param call: Callback.
    :param state: Состояние пользователя.
    :param user: Пользователь.
    :return:
    """
    text = user.personal_account_text()
    key = await inline.concatenate_key(
        await inline.menu_keyboard(),
        await inline.balance_history(),
        await inline.voucher_keyboard()
    )
    try:
        await call.message.edit_text(text, reply_markup=key)
    except Exception as e:
        logger.warning(e)
        await call.message.answer(text, reply_markup=key)
    await state.set_state(PersonalAccount.main)
